#include "sram.h"
#include "exceptions.h"

SRam::SRam (uint16_t size, uint16_t address_base)
  : DataBusMember (address_base)
{
  _size = size;
  _data = new uint8_t[_size - get_address_base ()];
}

SRam::~SRam ()
{
  delete [] _data;
}

uint8_t SRam::operator[] (uint16_t address) const
{
  if (address < 0 || address >= _size)
    throw MemoryException (address);

  return _data[address];
}

uint8_t& SRam::operator[] (uint16_t address)
{
  if (address < 0 || address >= _size)
    throw MemoryException (address);

  return _data[address];
}

void SRam::zero ()
{
  for (int i = 0; i < _size; ++i)
    _data[i] = 0;
}

uint8_t SRam::read (uint16_t address)
{
  int addr = address - get_address_base ();

  if (addr < 0 || addr >= _size)
    return DataBusMember::read (address);

  return _data[addr];
}

void SRam::write (uint16_t address, uint8_t data)
{
  int addr = address - get_address_base ();

  if (addr < 0 || addr >= _size) {
    DataBusMember::write (address, data);
    return;
  }

  _data[addr] = data;
}
